package com.tomtop;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.tomtop.base.model.Currency;
import com.tomtop.base.service.CurrencyService;
import com.tomtop.core.datasource.core.Proxy;
import com.tomtop.core.utils.JSONUtils;

@Component
public class MasterSlaveSwapTest implements CommandLineRunner {
	@Autowired CurrencyService currencyService;
	@Override
	public void run(String... args) throws Exception {
		/**
		 * 使用注解切换
		 */
		System.out.println("本次调用将使用默认的方式从主库查询");
		Currency currency = currencyService.findById(1);
		System.out.println(JSONUtils.toJSONString(currency));
		
		System.out.println("本次调用将从主库查询");
		currency = currencyService.findByIdOnMaster(1);
		System.out.println(JSONUtils.toJSONString(currency));
		
		System.out.println("本次调用将切换到从库查询");
		currency = currencyService.findByIdOnSalve(1);
		System.out.println(JSONUtils.toJSONString(currency));
		
		/**
		 * 使用代码切换
		 */
		System.out.println("本次调用将从主库查询");
		Optional<Currency> pcurrency = Proxy.master(()->currencyService.findById(1) );
		System.out.println(JSONUtils.toJSONString(pcurrency.get()));

		System.out.println("本次调用将切换到从库查询");
		pcurrency =Proxy.slave(()->currencyService.findById(1) );
		pcurrency =Proxy.slave(()->currencyService.findById(1) );
		System.out.println(JSONUtils.toJSONString(pcurrency.get()));
	}
}
